<template>
<div class="my-card">
  <div v-show="!showTable">
    <label for="waterFactory">水厂</label>
    <el-select class="select" id="waterFactory" v-model="waterFactory" placeholder="请选择" @change="getWaterPumpInfo">
      <el-option
        v-for="item in options1"
        :key="item.waterworksId"
        :label="item.name"
        :value="item.waterworksId">
      </el-option>
    </el-select>
    <label for="waterPump">水泵</label>
    <el-select class="select" id="waterPump" v-model="waterPumpId" placeholder="请选择">
      <el-option
        v-for="item in options2"
        :key="item.waterPumpId"
        :label="item.name"
        :value="item.waterPumpId">
      </el-option>
    </el-select>
    <el-date-picker
      v-model="curTime"
      type="datetime"
      placeholder="测试时间">
    </el-date-picker>
    <el-button class="my-btn" type="primary" @click="getData">查询</el-button>
    <el-button class="my-btn float-right" type="primary" @click="changePages">测试数据</el-button>
    <v-chart class="chartBox" :options="lineOption"/>
  </div>
  <div v-show="showTable">
    <el-tabs v-model="activeName" type="card">
      <el-tab-pane label="当前测试数据" name="first" class="curTestData">
        <div class="toolbar">
          <el-date-picker
            id="curTime"
            @change="getData"
            v-model="curTime"
            type="datetime"
            placeholder="当前测试时间">
          </el-date-picker>
          <div class="btns">
            <el-button type="primary" @click="handleEdit">编辑</el-button>
            <el-button type="primary" @click="handleSave">保存</el-button>
            <el-button type="primary" @click="changePages">更新</el-button>
            <el-button type="primary" @click="handleAdd" icon="el-icon-plus" round style="padding: 12px"></el-button>
          </div>
        </div>
        <el-table
          :data="tapData"
          style="width: 100%"
          >
          <el-table-column
            label="流量"
            prop="q"
            width="180">
            <template slot-scope="scope">
              <el-input v-show="!scope.row.show" size="small" v-model="scope.row.flow" placeholder="请输入内容"></el-input>
              <span v-show="scope.row.show" >{{scope.row.flow}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="h"
            label="扬程">
            <template slot-scope="scope">
              <el-input v-show="!scope.row.show" size="small" v-model="scope.row.head" placeholder="请输入内容"></el-input>
              <span v-show="scope.row.show" >{{scope.row.head}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="p"
            label="功率">
            <template slot-scope="scope">
              <el-input v-show="!scope.row.show" size="small" v-model="scope.row. power" placeholder="请输入内容"></el-input>
              <span v-show="scope.row.show" >{{scope.row.power}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="e"
            label="效率">
            <template slot-scope="scope">
              <el-input v-show="!scope.row.show" size="small" v-model="scope.row.effRate" placeholder="请输入内容"></el-input>
              <span v-show="scope.row.show" >{{scope.row.effRate}}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作">
            <template slot-scope="scope">
              <el-button type="text" @click="handleDelete(scope.$index, scope.row)" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="历史测试数据" name="second">
        <div class="toolbar">
          <DatePicker
            :options="options"
            :getData="getHData"
          >
          </DatePicker>
          <!-- <a ref="downlink"></a> -->
          <!-- <el-button type="primary" @click="downloadFile(excelData)" class="export">导出</el-button> -->
        </div>
        <el-table
          :data="historyData"
          style="width: 100%"
          :default-sort = "{prop: 'flow', order: 'descending'}"
          >
          <el-table-column
            prop="flow"
            label="流量"
            sortable
            width="180">
          </el-table-column>
          <el-table-column
            sortable
            prop="head"
            label="扬程">
          </el-table-column>
          <el-table-column
            sortable
            prop="power"
            label="功率">
          </el-table-column>
          <el-table-column
            sortable
            prop="effRate"
            label="效率">
          </el-table-column>
        </el-table>
      </el-tab-pane>
    </el-tabs>
  </div>
</div>
</template>

<script>
import ECharts from 'vue-echarts/components/ECharts'
import ecStat from 'echarts-stat'
import DatePicker from '../components/DatePicker.vue'
import moment from 'moment'
// import XLSX from 'xlsx'
import { getCurTestData, setCurTestData, getHistoryData, getPumpsInfo } from './model'

export default {
  name: 'WaterPump',
  data () {
    return {
      historyData: [],
      outfile: '',
      activeName: 'first',
      showTable: false,
      waterPumpId: '',
      waterFactory: '',
      options1: [{
        value: '0',
        label: '第1净化水厂'
      }, {
        value: '1',
        label: '第2净化水厂'
      }, {
        value: '2',
        label: '第3净化水厂'
      }],
      options2: [{
        value: 1,
        label: '1#泵'
      }, {
        value: 2,
        label: '2#泵'
      }, {
        value: 3,
        label: '3#泵厂'
      }],
      curTime: new Date(),
      lineOption: {},
      tapData: [],
      options: [{
        text: '最近一月',
        range: [moment().subtract(1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      }, {
        text: '最近一年',
        range: [moment().subtract(1, 'y').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')]
      }]
    }
  },
  components: {
    'v-chart': ECharts,
    DatePicker
  },
  mounted () {
    this.getData()
    this.getPumpsInfo()
  },
  methods: {
    getData () {
      let params = {
        waterPumpId: this.waterPumpId || 1,
        curTime: moment(this.curTime).format('x')
      }
      getCurTestData(params).then((res) => {
        this.tapData = res.data.data.testData
        this.tapData = this.tapData.map(item => {
          return {...item, show: true}
        })
        this.initEchart()
      }).catch((err) => {
        console.log(err)
      })
      this.getHData([moment().subtract(1, 'M').format('YYYY-MM-DD'), moment().format('YYYY-MM-DD')])
    },
    getPumpsInfo () {
      getPumpsInfo().then(res => {
        console.log(res)
        this.options1 = res.data.data.waterworksInfo
      })
    },
    getWaterPumpInfo(value) {
      let selectPump =  this.options1.filter(item => {
        return item.waterworksId === value
      })
      console.log(selectPump[0].waterpumpsInfo)
      this.options2 = selectPump[0].waterpumpsInfo
    },
    getHData (date) {
      let params2 = {
        waterPumpId: this.waterPumpId || 1,
        startTime: moment(date[0]).format('x'),
        endTime: moment(date[1]).format('x')
      }
      getHistoryData(params2).then(res => {
        this.historyData = res.data.data.testData
      })
    },
    handleEdit () {
      this.tapData = this.tapData.map(item => {
        return {...item, show: false}
      })
    },
    handleSave () {
      setCurTestData({
        name: '三坪水厂1#泵',
        testTime: 100,
        waterPumpId: this.waterPumpId || 1,
        testData: this.tapData.filter(item => {
          delete item.testTime
          delete item.show
          return item
        })
      }).then((res) => {
        this.tapData = this.tapData.map(item => {
          return {...item, show: true}
        })
      })
    },
    handleDelete (index, row) {
      this.tapData.splice(index, 1)
    },
    handleAdd () {
      this.tapData.push({
        flow: 0,
        head: 0,
        power: 0,
        effRate: 0,
        show: false
      })
    },
    changePages () {
      this.showTable = !this.showTable
      if (!this.showTable) {
        this.initEchart()
      }
    },
    initEchart () {
      let points = [[], [], []]
      let myRegression = [[], [], []]
      let series = []
      let color = ['#c23531', '#2f4554', '#61a0a8']
      this.tapData.map((item, index) => {
        if (item) {
          points[0].push([item.flow, item.head])
          points[1].push([item.flow, item.power])
          points[2].push([item.flow, item.effRate])
        }
      })
      points.forEach((item, index) => {
        myRegression[index] = ecStat.regression('polynomial', points[index], 2)
        myRegression[index].points.sort((a, b) => (a[0] - b[0]))
        series.push({
          name: '扬程',
          type: 'scatter',
          data: item,
          itemStyle: {
            color: color[index]
          }
        }, {
          name: 'line',
          type: 'line',
          smooth: true,
          showSymbol: false,
          data: myRegression[index].points,
          itemStyle: {
            normal: {
              lineStyle: {
                color: color[index]
              }
            }
          },
          markPoint: {
            itemStyle: {
              normal: {
                color: 'transparent'
              }
            },
            label: {
              normal: {
                show: true,
                position: 'left',
                formatter: myRegression[index].expression,
                textStyle: {
                  color: '#333',
                  fontSize: 14
                }
              }
            },
            data: [{
              coord: myRegression[index].points[myRegression[index].points.length - 1]
            }]
          }
        })
      })
      this.lineOption = {
        xAxis: {
          min: 'dataMin'
        },
        yAxis: {},
        series,
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'line',
            snap: true
          }
        },
        grid: {
          left: '2%',
          right: '2%',
          containLabel: true
        }
      }
    }
  }
}
// downloadFile () {
//   let rs = this.tapData
//   let data = [{}]
//   for (let k in rs[0]) {
//     data[0][k] = k
//   }
//   data = data.concat(rs)
//   this.downloadExl(data, '菜单')
// },
// downloadExl (json, downName, type) { // 导出到excel
//   let keyMap = [] // 获取键
//   for (let k in json[0]) {
//     keyMap.push(k)
//   }
//   console.info('keyMap', keyMap, json)
//   let tmpdata = [] // 用来保存转换好的json
//   json.map((v, i) => keyMap.map((k, j) => Object.assign({}, {
//     v: v[k],
//     position: (j > 25 ? this.getCharCol(j) : String.fromCharCode(65 + j)) + (i + 1)
//   }))).reduce((prev, next) => prev.concat(next)).forEach(function (v) {
//     tmpdata[v.position] = {
//       v: v.v
//     }
//   })
//   let outputPos = Object.keys(tmpdata) // 设置区域,比如表格从A1到D10
//   let tmpWB = {
//     SheetNames: ['mySheet'], // 保存的表标题
//     Sheets: {
//       'mySheet': Object.assign({},
//         tmpdata, // 内容
//         {
//           '!ref': outputPos[0] + ':' + outputPos[outputPos.length - 1] // 设置填充区域
//         })
//     }
//   }
//   let tmpDown = new Blob([this.s2ab(XLSX.write(tmpWB,
//     {bookType: (type === undefined ? 'xlsx' : type), bookSST: false, type: 'binary'} // 这里的数据是用来定义导出的格式类型
//   ))], {
//     type: ''
//   }) // 创建二进制对象写入转换好的字节流
//   var href = URL.createObjectURL(tmpDown) // 创建对象超链接
//   this.outFile.download = downName + '.xlsx' // 下载名称
//   this.outFile.href = href // 绑定a标签
//   this.outFile.click() // 模拟点击实现下载
//   setTimeout(function () { // 延时释放
//     URL.revokeObjectURL(tmpDown) // 用URL.revokeObjectURL()来释放这个object URL
//   }, 100)
// },
</script>

<style lang="sass" scoped>
.my-card
  width: 100%;
  background-color: #fff;
  padding: 15px;
  margin: 10px;
  .toolbar /deep/ .el-date-editor
    width: 350px;
    justify-content: space-between;
label
  margin-right: 5px;
.select
  margin-right: 10px;
.chartBox
  width: 100%;
.float-right
  float: right;
.toolbar
  margin-bottom: 10px;
.curTestData
  .toolbar
    display: flex;
    justify-content: space-between;
.export
  position: absolute;
  top: 0;
  right: 0;
</style>
